package com.example.coolweather;

import static com.example.coolweather.constants.Constants.AQI_URL;
import static com.example.coolweather.constants.Constants.FORECAST_URL;
import static com.example.coolweather.constants.Constants.KEY;
import static com.example.coolweather.constants.Constants.NOWWEATHER_URL;
import static com.example.coolweather.constants.Constants.PIC_URL;
import static com.example.coolweather.constants.Constants.SUGGEST_URL;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;

import com.bumptech.glide.Glide;
import com.example.coolweather.databinding.ActivityWeatherBinding;
import com.example.coolweather.databinding.ForecastItemBinding;
import com.example.coolweather.gson.AQI;
import com.example.coolweather.gson.BingPic;
import com.example.coolweather.gson.Forecast;
import com.example.coolweather.gson.NowWeather;
import com.example.coolweather.gson.Suggest;
import com.example.coolweather.util.HttpUtil;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    ActivityWeatherBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        getWindow().setStatusBarColor(Color.TRANSPARENT);



        binding=ActivityWeatherBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.includeTitle.titleCity.setOnClickListener(v->
                binding.drawerLayout.openDrawer(GravityCompat.START));


        Intent intent=getIntent();
        String spot = intent.getStringExtra("spot");
        String location=intent.getStringExtra("location");
        Log.d("test2", "onCreate: "+spot+":"+location);

        showTitle(spot);

        requestWeather(location);
        loadBIngPic();
    }

    private void loadBIngPic() {
        HttpUtil.sendOkHttpRequest(PIC_URL, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(()->{
                    Toast.makeText(WeatherActivity.this, "每日一图访问失败", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String strJson = response.body().string();
                BingPic bingPic =gson.fromJson(strJson,BingPic.class);
                if (bingPic!=null&& bingPic.getCode()==200){
                    runOnUiThread(()->{
                        Glide.with(WeatherActivity.this).load(bingPic.getData().getUrl()).into(binding.bingPicImg);
                    });
                }
            }
        });
    }

    private void requestWeather(String location) {
        String url=String.format(NOWWEATHER_URL,location,KEY);
        Log.d("test", "requestWeather: "+url);
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String strJson=response.body().string();
                Log.d("test", "requestWeather: "+strJson);
                NowWeather nowWeather = gson.fromJson(strJson, NowWeather.class);
                if(nowWeather.getCode().equals("200")){
                    Log.d("test", String.format("当前气温:%s ℃，天气情况：%s",nowWeather.getNow().getTemp(),nowWeather.getNow().getText()));
                    showNowWeather(nowWeather);
                }else {
                    Log.d("test", "访问实时天气API出错");
                }

            }

            private void showNowWeather(NowWeather nowWeather) {
                runOnUiThread(()->{
                    binding.includeNow.degreeText.setText(nowWeather.getNow().getTemp()+"℃");
                    binding.includeNow.weatherInfoText.setText(nowWeather.getNow().getText());
                });
            }
        });

        String url_aqi=String.format(AQI_URL,location,KEY);
        Log.d("test", "requestWeather: "+url_aqi);
        HttpUtil.sendOkHttpRequest(url_aqi, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String strJson=response.body().string();
                Log.d("test", "aqi"+strJson);
                AQI aqi = gson.fromJson(strJson, AQI.class);
                if(aqi.getCode().equals("200")){

                    showAQI(aqi);
                }else {
                    Log.d("test", "访问实时天气API出错");
                }

            }

            private void showAQI(AQI aqi) {
                runOnUiThread(()->{
                    binding.includeAqi.aqiText.setText(aqi.getNow().getAqi());
                    binding.includeAqi.pm25Text.setText(aqi.getNow().getPm2p5());
                });
            }
        });

        String url_suggest=String.format(SUGGEST_URL,location,KEY);
        Log.d("test", "requestWeather: "+url_suggest);
        HttpUtil.sendOkHttpRequest(url_suggest, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String strJson=response.body().string();
                Log.d("test", "suggest"+strJson);
                Suggest suggest = gson.fromJson(strJson, Suggest.class);
                if(suggest.getCode().equals("200")){
                    showSUGGEST(suggest);
                }else {
                    Log.d("test", "访问实时天气API出错");
                }

            }
            private void showSUGGEST(Suggest suggest){
                runOnUiThread(() -> {
                    binding.includeSuggestion.wearText.setText(suggest.getDaily().get(0).getText());
                    binding.includeSuggestion.sportText.setText(suggest.getDaily().get(1).getText());
                    binding.includeSuggestion.comfortText.setText(suggest.getDaily().get(2).getText());
                });
            }

        });


        String url_forecast=String.format(FORECAST_URL,location,KEY);
        HttpUtil.sendOkHttpRequest(url_forecast, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String strJson=response.body().string();
                Forecast forecast=gson.fromJson(strJson,Forecast.class);
                if (forecast.getCode().equals("200")){
                    showForecast(forecast);
                }else {
                    Log.d("test", "访问实时天气API出错");
                }
            }

            private void showForecast(Forecast forecast) {
                runOnUiThread(()->{
                    binding.includeForecast.forecastLayout.removeAllViews();
                    for (Forecast.DailyDTO dailyDTO:forecast.getDaily()){
                        ForecastItemBinding binding_item=ForecastItemBinding.inflate(getLayoutInflater());
                        binding_item.dateText.setText(dailyDTO.getFxDate());
                        binding_item.infoText.setText(dailyDTO.getTextDay());
                        binding_item.maxText.setText(dailyDTO.getTempMax());
                        binding_item.minText.setText(dailyDTO.getTempMin());

                        View child = binding_item.getRoot();
                        binding.includeForecast.forecastLayout.addView(child);}
                });


            }
        });
    }




    Gson gson=new Gson();
    private void showTitle(String spot) {
        binding.includeTitle.titleCity.setText(spot);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        binding.includeTitle.titleUpdateTime.setText(format.format(new Date()));
    }
}